package com.sctvcloud.zhaohua_sd.ui.fragment;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.githang.statusbar.StatusBarCompat;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.widget.CustomCheckBox;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.PermissionUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.ruihang.generalibrary.utils.TimeObserve;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.base.BaseFragment;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.beans.FVersionInfo;
import com.sctvcloud.zhaohua_sd.beans.MessageStateBean;
import com.sctvcloud.zhaohua_sd.beans.UserInfoBean;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.activities.AboutActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.ChooseCityActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.EarnIntegralActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.HelpCenterActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.HistoriesActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.IntegralStoreActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.InvitationCodeActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.LiveBroadcastActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.LoginActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.MineSettingActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.MyAnchorDyActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.MyCollectionActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.MyMessageCenterActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.MyPageActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.MySubscribeActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.RebllionActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.SearchNewsActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.ShareAnchorActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.SignInActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.UserInfoActivity;
import com.sctvcloud.zhaohua_sd.ui.dialog.CheckPermission;
import com.sctvcloud.zhaohua_sd.ui.dialog.FontSizeDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.dialog.ShowDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.manager.AdPictureManager;
import com.sctvcloud.zhaohua_sd.ui.manager.MessageManager;
import com.sctvcloud.zhaohua_sd.ui.utils.GlideCircleTransform;
import com.sctvcloud.zhaohua_sd.ui.utils.GlideUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.cache.DataCleanManager;
import com.sctvcloud.zhaohua_sd.ui.utils.update.DownloadManager;
import com.sctvcloud.zhaohua_sd.utils.UserManager;
import com.sctvcloud.zhaohua_sd.utils.VersionUtil;

import java.util.ArrayList;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrator on 2017/6/26 0026.
 * 我的 （设置）
 */
public class MineFragment extends BaseFragment {
    private final int GET_MESSAGE_STATUS = 101;
    private final int REQUEST_CODE_LOGIN = 201;
    private final int REQUEST_CODE_INFO = 202;
    private final int REQUEST_CODE_ANCHOR = 203;
    private final int REQUEST_CODE_INVITATION = 204;
    private final int TO_MESSAGE_CENTER = 205;
    private final int TO_SIGN_IN = 206;
    @BindView(R.id.title_top_logo)
    protected ImageView homeLog;
    @BindView(R.id.mine_icon)
    protected ImageView mine_icon;
    @BindView(R.id.mine_username)
    protected CustomFontTextView mine_userName;
    @BindView(R.id.mine_anchor_lay)
    protected LinearLayout anchorLay;
    @BindView(R.id.mine_share_anchor)
    protected LinearLayout shareSchorLay;
    @BindView(R.id.mine_anchor_edit)
    protected LinearLayout anchorEditLay;
    @BindView(R.id.mine_living)
    protected LinearLayout sendLiving;
    @BindView(R.id.mine_login)
    protected LinearLayout login;
    @BindView(R.id.to_sign_in)
    protected CustomFontTextView signIn;
    @BindView(R.id.message_center)
    protected ImageView messageCenter;
    @BindView(R.id.title_top_back)
    protected ImageView backImg;

    @BindView(R.id.mine_deivider)
    protected View divider;
    private FontSizeDiaFragment fontSizeDiaFragment;
    private ShowDiaFragment showDiaFragment;
    public static final String FONT_TAG = "dia_font_size_fragment";
    public static final String SHOW_TAG = "dia_show_fragment";

    //最新的切换到“我的”页面的时间戳
    private long lastShowTime = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        Cache.getInstance().setCurrentChannelId("");
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        isCoverStatusColor = false;
        super.onViewCreated(view, savedInstanceState);
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.blue_main));
//        homeLog.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(getContext(), ChooseCityActivity.class);
//                startActivity(intent);
//            }
//        });
        backImg.setVisibility(View.GONE);
        checkUser();
        intMessageService();
        initUserData();
    }


    @Override
    public void onResume() {
        super.onResume();
        checkUser();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            long now = System.currentTimeMillis();
            if (now - lastShowTime > 30 * 1000) {
                lastShowTime = now;
                requestMessageData();
                initUserData();
            }
            checkUser();
            Cache.getInstance().setCurrentChannelId("");
            StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.blue_main));
        }
    }

    /**
     * 启动定时获取消息状态服务(暂定5分钟一次)
     */
    private void intMessageService() {
        MessageManager messageManager = new MessageManager(getContext());
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null && msg.what == GET_MESSAGE_STATUS) {
                    requestMessageData();
                }
            }
        };
        messageManager.startMessageService(handler, GET_MESSAGE_STATUS);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        TimeObserve.removeObserS(getOwnerName());
    }


    /**
     * 判断用户是否登录
     */
    private void checkUser() {

        if (null != UserManager.getInstance().getUser()) {
            initUser();
            signIn.setVisibility(View.VISIBLE);
        } else {
            mine_userName.setText(R.string.login_or_register);
            mine_icon.setImageResource(R.mipmap.icon_circle_avatar);
            anchorLay.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
            sendLiving.setVisibility(View.GONE);
            signIn.setVisibility(View.GONE);
            messageCenter.setImageResource(R.mipmap.mine_message_un);
        }
    }

    /**
     * 初始化显示用户信息
     * 调用前需检查非空
     */
    private void initUser() {
        if (UserManager.getInstance().getUser() == null) {
            return;
        }
        mine_userName.setText(UserManager.getInstance().getUser().getNickName());
        String icon = UserManager.getInstance().getUser().getAvatar();
        if (!TextUtils.isEmpty(icon)) {
            GlideUtil.getDynamicGlid(getContext(), icon, true).transform(new GlideCircleTransform(getContext()))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(mine_icon);
        }
        int type = UserManager.getInstance().getUser().getUserType();
//        if (type == Constances.USER_TYPE_ANCHOR) {
//            anchorLay.setVisibility(View.VISIBLE);
//            sendLiving.setVisibility(View.VISIBLE);
//            divider.setVisibility(View.VISIBLE);
//        } else if (type == Constances.USER_TYPE_REPORTER) {
//            anchorLay.setVisibility(View.GONE);
//            divider.setVisibility(View.GONE);
//            sendLiving.setVisibility(View.VISIBLE);
//        } else {
//            anchorLay.setVisibility(View.GONE);
//            divider.setVisibility(View.GONE);
//            sendLiving.setVisibility(View.GONE);
//        }
    }

    /**
     * 请求用户相关数据，积分等
     */
    private void initUserData() {
        if (UserManager.getInstance().isLogin()) {
            //TODO 查询用户积分数据
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetUserData(getOwnerName(), p, new AbsNetCallBack<UserInfoBean>(UserInfoBean.class) {
                @Override
                public void onSuc(UserInfoBean userInfoBean) {
                    Cache.getInstance().setUserInfo(userInfoBean);
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                    checkUser();
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }

                @Override
                public boolean whenLoginExpiredBackGround() {//正常测试时删除此方法
                    JLog.e("", "initUserData whenLoginExpiredBackGround");
                    return true;
                }
            });
        }
    }

    /**
     * 请求消息 是否有未读消息
     */

    private void requestMessageData() {
        if (!UserManager.getInstance().isLogin()) {
            messageCenter.setImageResource(R.mipmap.mine_message_un);
        } else {
            //TODO 查询消息数据
//            messageCenter.setImageResource(R.mipmap.mine_message);
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetMessageState(getOwnerName(), p, new AbsNetCallBack<MessageStateBean>(MessageStateBean.class) {
                @Override
                public void onSuc(MessageStateBean messageStateBean) {
                    JLog.e("MessageData ", "count = " + messageStateBean.getCount());
                    if (messageStateBean.getCount() > 0) {
                        messageCenter.setImageResource(R.mipmap.mine_message);
                    } else {
                        messageCenter.setImageResource(R.mipmap.mine_message_un);
                    }
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                    checkUser();
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                    messageCenter.setImageResource(R.mipmap.mine_message_un);
                }

                @Override
                public boolean whenLoginExpiredBackGround() {//正常测试时删除此方法
                    JLog.e("", "requestMessageData whenLoginExpiredBackGround");
                    return true;
                }
            });
        }
    }

    @OnClick({R.id.mine_living, R.id.mine_share_anchor, R.id.mine_points_layout, R.id.mine_anchor_edit})
    public void itemClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "设置"));
        pairs.add(new Pair<>("行为类型", "点击"));
        switch (view.getId()) {
            case R.id.mine_living:
                //发起直播
                Intent intent = new Intent(getContext(), LiveBroadcastActivity.class);
                startActivity(intent);
                break;
            case R.id.mine_share_anchor:
                //分享到主播圈
                Intent shareIntent = new Intent(getContext(), ShareAnchorActivity.class);
                startActivityForResult(shareIntent, REQUEST_CODE_ANCHOR);
                break;
            case R.id.mine_anchor_edit:
                //主播动态管理
                Intent anchorEdit = new Intent(getContext(), MyAnchorDyActivity.class);
                startActivity(anchorEdit);
                break;
        }
    }

    @OnClick({R.id.mine_points_layout, R.id.mine_integral_mall, R.id.mine_setting, R.id.mine_help_center, R.id.mine_telephone_ll, R.id.to_sign_in, R.id.message_center_layout,R.id.mine_apply})
    public void mineClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "设置"));
        pairs.add(new Pair<>("行为类型", "点击"));
        switch (view.getId()) {
            case R.id.mine_points_layout:
                //需要先登录
                if (isLogin()) {
                    JLog.e("mineClick", "  赚取积分");
                    GridsumWebDissector.getInstance().trackEvent(this, "", "赚取积分", "", 200, pairs);
                    Intent intent = new Intent(getContext(), EarnIntegralActivity.class);
                    startActivityForResult(intent, TO_SIGN_IN);
                } else {
                    toLogin();
                }
                break;
            case R.id.mine_integral_mall:
                //需要先登录
                if (isLogin()) {
                    GridsumWebDissector.getInstance().trackEvent(this, "", "积分商城", "", 200, pairs);
                    IntegralStoreActivity.startThis(getContext());
                    JLog.e("mineClick", "  积分商城");
                } else {
                    toLogin();
                }
                break;
            case R.id.mine_setting:
                GridsumWebDissector.getInstance().trackEvent(this, "", "设置", "", 200, pairs);
                JLog.e("mineClick", "  设置");
                Intent setting = new Intent(getContext(), MineSettingActivity.class);
                startActivity(setting);
                break;
            case R.id.mine_help_center:
                JLog.e("mineClick", "  帮助中心");
                GridsumWebDissector.getInstance().trackEvent(this, "", "帮助中心", "", 200, pairs);
                Intent helpIntent = new Intent(getActivity(), HelpCenterActivity.class);
                startActivity(helpIntent);
                break;
            case R.id.mine_telephone_ll:
                JLog.e("mineClick", "  客服电话");
                GridsumWebDissector.getInstance().trackEvent(this, "", "客服电话", "", 200, pairs);
                showDialog(1);
                break;
            case R.id.to_sign_in:
                //需要先登录
                if (isLogin()) {
                    JLog.e("mineClick", "签到赚积分");
                    GridsumWebDissector.getInstance().trackEvent(this, "", "签到赚积分", "", 200, pairs);
                    Intent signIn = new Intent(getActivity(), SignInActivity.class);
                    startActivity(signIn);
                } else {
                    toLogin();
                }
                break;
            case R.id.message_center_layout:
                //需要先登录
                if (isLogin()) {
                    JLog.e("mineClick", "  消息中心");
                    GridsumWebDissector.getInstance().trackEvent(this, "", "消息中心", "", 200, pairs);
                    Intent msgIntent = new Intent(getActivity(), MyMessageCenterActivity.class);
                    startActivityForResult(msgIntent, TO_MESSAGE_CENTER);
                } else {
                    toLogin();
                }
//                Intent msgIntent = new Intent(getActivity(), SearchNewsActivity.class);
//                startActivity(msgIntent);
                break;
            case R.id.mine_apply:
                //需要先登录
                if (isLogin()) {
                    GridsumWebDissector.getInstance().trackEvent(this, "", "我的诉求", "", 200, pairs);
                    Intent intent = new Intent(getActivity(), MyPageActivity.class);
                    startActivity(intent);
                } else {
                    toLogin();
                }

                break;
        }
    }


    /**
     * 对应点击事件
     *
     * @param view
     */
    @OnClick(value = {R.id.mine_login_subscribe, R.id.mine_login_collection, R.id.mine_login_invitation_number, R.id.mine_login_history})
    public void loginClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "设置"));
        pairs.add(new Pair<>("行为类型", "点击"));
        switch (view.getId()) {
            case R.id.mine_login_subscribe:
                GridsumWebDissector.getInstance().trackEvent(this, "", "我的预约", "", 200, pairs);
                // String url = (String) SharedPreferencesUtil.getParam(getContext(), SUBSCRIBE_KEY, "");
                Intent intent = new Intent(getContext(), MySubscribeActivity.class);
                intent.putExtra(BaseActivity.EX_TYPE, 2);
                //intent.putExtra(BaseActivity.EX_URL, "url");
                startActivity(intent);
                break;
            case R.id.mine_login_collection:
                GridsumWebDissector.getInstance().trackEvent(this, "", "我的收藏", "", 200, pairs);
                Intent collectionIntent = new Intent(getActivity(), MyCollectionActivity.class);
                startActivity(collectionIntent);
                break;
            case R.id.mine_login_invitation_number:
                //需要先登录
                if (isLogin()) {
                    GridsumWebDissector.getInstance().trackEvent(this, "", "我的邀请码", "", 200, pairs);
                    Intent invitationIntent = new Intent(getActivity(), InvitationCodeActivity.class);
                    startActivityForResult(invitationIntent, REQUEST_CODE_INVITATION);
                } else {
                    toLogin();
                }
                break;
            case R.id.mine_login_history:
                GridsumWebDissector.getInstance().trackEvent(this, "", "历史记录", "", 200, pairs);
                Intent historiesIntent = new Intent(getActivity(), HistoriesActivity.class);
                startActivity(historiesIntent);
                break;
        }
    }

    @OnClick(value = {R.id.mine_icon, R.id.mine_username})
    public void userLoginClick(View view) {
        //点击用户区域，按条件进入用户信息页面或者进入登录页
        if (isLogin()) {
            Intent intent = new Intent(getContext(), UserInfoActivity.class);
            startActivityForResult(intent, REQUEST_CODE_INFO);
        } else {
            toLogin();
        }
    }


    /**
     * 切换字体后回调刷新UI
     *
     * @param what
     */
    private void parseWhat(int what) {
        if (what == ShowDiaFragment.PHONE_TAG) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + getString(R.string.mine_telephone_number)));
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                toast(R.string.failed_to_phone);
            }
        }
    }

    private void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, REQUEST_CODE_LOGIN);
    }

    //Dialog点击回调
    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            parseWhat(msg.what);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOGIN) {
            if (resultCode == LoginActivity.RESULT_OK) {
                initUser();
                //用户登录成功，刷新消息状态
                requestMessageData();
                initUserData();
            }
        } else if (requestCode == REQUEST_CODE_INFO) {
            initUser();
            //从账户信息页回来，判断如果用户已经退出登录，则修改消息显示
            if (UserManager.getInstance().getUser() == null) {
                messageCenter.setImageResource(R.mipmap.mine_message_un);
            }
        } else if (requestCode == REQUEST_CODE_ANCHOR) {
            if (resultCode != 0) {
                checkUser();
            }
        } else if (requestCode == REQUEST_CODE_INVITATION) {
            checkUser();
        } else if (requestCode == TO_MESSAGE_CENTER && resultCode == getActivity().RESULT_OK) {
            requestMessageData();
        } else if (requestCode == TO_SIGN_IN) {
            initUserData();
            requestMessageData();
        }
    }

    private boolean isLogin() {
        return UserManager.getInstance().isLogin();
//        return    null!=UserManager.getInstance().getUser()  ;
    }

    /**
     * 弹出提示框
     *
     * @param type 0 是否退出登录， 1 是否拨打客服
     */
    private void showDialog(int type) {
//        if (showDiaFragment == null) {
        showDiaFragment = new ShowDiaFragment();
//        }
        showDiaFragment.setCallBack(callBack);
        showDiaFragment.setType(type);
        showDiaFragment.show(getActivity().getSupportFragmentManager(), SHOW_TAG);
    }
}
